<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Chat extends MY_Controller
{

    private $redis = '';

    public function __construct()
    {
        parent::__construct();
        $this->load->model('ChatSession');
        $this->load->model('ChatComment');
        $this->load->model('ChatRecord');
        $this->load->model('CustomerInfo');
    }

    public function index()
    {
        $this->webChat();
    }

    /* 在线客服界面 */
    public function webChat()
    {
        $data = array();
        /* 获取用户名 */
        $user = $this->session->user;
        $username = $user['username'];
        $data['username'] = $username;
        $this->load->view('chat/onlineOpen', $data);
    }

    /* 获取用户聊天记录 */
    public function getSession()
    {
        $time = time() - 3600 * 24;
        $time = strtotime(date('Ymd', $time)); // 获取最近前天和当天的历史记录
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $sessionId = isset($_REQUEST['sessionId']) ? trim($_REQUEST['sessionId']) : '';
        $type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : 'current';
        $user = $this->session->user;
        $username = $user['username'];
        
        if (empty($sessionId)) {
            $data['msg'] = 'sessionId不能为空！';
            echo json_encode($data);
            return false;
        }
        $robotId = WEBCHAT_ROBOT_ID;
        switch ($type) {
            case 'current':
                $condition = "ctime >= $time and ((sender = '$sessionId' and receiver = '$username') or (sender = '$username' and receiver = '$sessionId') or (sender = '$sessionId' and receiver = '$robotId') or (sender = '$robotId' and receiver = '$sessionId'))";
                break;
            case 'history':
                $condition = "sender = '$sessionId' or receiver = '$sessionId'";
                break;
            default:
                $data['msg'] = 'type错误！';
                echo json_encode($data);
                return false;
        }
        $field = array();
        $result = $this->ChatRecord->find($condition, $field, 'ctime asc, id asc');
        $sql = $this->db->last_query();
        if (empty($result)) {
            $data = array(
                'code' => 1,
                'msg' => '未查询到记录',
                'res' => array()
            );
            echo json_encode($data);
            return false;
        }
        $res = array();
        $senderHeadImage = sprintf(HEXIN_USER_HEAD_IMAGE, $sessionId % 10000, $sessionId);
        foreach ($result as $k => $v) {
            $tmp['id'] = $v['id'];
            $tmp['time'] = date('Y-m-d H:i:s', $v['ctime']);
            $tmp['message'] = $v['comment'];
            $tmp['senderId'] = $v['sender'];
            $tmp['snederName'] = ($robotId == $v['sender_name']) ? '同花顺智能机器人' : $v['sender_name'];
            if ($sessionId == $v['sender']) {
                $tmp['headImage'] = $senderHeadImage;
                $tmp['userFlag'] = 0;
            } elseif ($robotId == $v['sender_name']) {
                $tmp['headImage'] = base_url() . WEBCHAT_ROBOT_HEAD_IMAGE;
                $tmp['userFlag'] = 1;
            } else {
                $tmp['headImage'] = DEFAULT_HEAD_IMAGE;
                $tmp['userFlag'] = 1;
            }
            $res[] = $tmp;
        }
        $data = array(
            'code' => 1,
            'msg' => '查询成功！',
            'res' => $res
        );
        echo json_encode($data);
    }

    /* 获取当前回话和历史会话列表 */
    public function getSessionList()
    {
        $data = array(
            'code' => 1,
            'msg' => '获取列表成功！'
        );
        /* 获取用户名 */
        $user = $this->session->user;
        $username = $user['username'];
        /* 获取当前会话列表 */
        $condition = array(
            'receiver' => $username,
            'state' => 1
        );
        $field = array(
            'sender',
            'sender_name',
            'message_number'
        );
        $order = 'update_time desc';
        $result = $this->ChatSession->find($condition, $field, $order);
        $data['currentSessionList'] = array();
        if (! empty($result)) {
            $currentSessionList = array();
            foreach ($result as $k => $v) {
                $tmp['userid'] = $v['sender'];
                $tmp['username'] = $v['sender_name'];
                $tmp['messageNumber'] = $v['message_number'];
                $tmp['headImage'] = sprintf("%s", $v['sender'] % 10000, $v['sender']);
                /* 检查该用户是否在线 */
                $online = $this->isOnline($v['sender']);
                $tmp['online'] = $online ? 1 : 0;
                $currentSessionList[] = $tmp;
            }
            $data['currentSessionList'] = $currentSessionList;
            /* 关闭redis连接 */
            if ($this->redis) {
                $this->redis->close();
            }
        }
        /* 获取历史会话列表 */
        $condition = array(
            'receiver' => $username,
            'state' => 2
        );
        $limit = array(
            'number' => 100,
            'start' => 0
        );
        $data['historySessionList'] = array();
        $result = $this->ChatSession->find($condition, $field, $order, $limit);
        if (! empty($result)) {
            $historySessionList = array();
            foreach ($result as $k => $v) {
                $tmp['userid'] = $v['sender'];
                $tmp['username'] = $v['sender_name'];
                $tmp['headImage'] = sprintf("%s", $v['sender'] % 10000, $v['sender']);
                $historySessionList[] = $tmp;
            }
            $data['historySessionList'] = $historySessionList;
        }
        echo json_encode($data);
    }

    /* 当前回话和历史会话的切换 */
    public function sessionSet()
    {
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 1; // type=1:从当前切换到历史；type=2:从历史移除；type=3:从历史移到当前
        $sender = isset($_REQUEST['userid']) ? trim($_REQUEST['userid']) : '';
        if (empty($sender)) {
            $data['msg'] = 'userid不能为空!';
            echo json_encode($data);
            return false;
        }
        $user = $this->session->user;
        $username = $user['username'];
        $condition = array(
            'sender' => $sender,
            'receiver' => $username
        );
        $value = array();
        switch ($type) {
            case '1':
                $state = 2;
                $value['message_number'] = 0;
                break;
            case '2':
                $state = 0;
                break;
            case '3':
                $state = 1;
                break;
            default:
                $data['msg'] = 'type类型错误！';
                echo json_encode($data);
                return false;
        }
        $value['state'] = $state;
        $result = $this->ChatSession->update($condition, $value);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '操作成功！';
        } else {
            $data['msg'] = '操作失败！';
        }
        echo json_encode($data);
    }

    /* 消除小红点 */
    public function eliminateRedSpots()
    {
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $sender = isset($_REQUEST['userid']) ? trim($_REQUEST['userid']) : '';
        if (empty($sender)) {
            $data['msg'] = 'userid不能为空!';
            echo json_encode($data);
            return false;
        }
        $user = $this->session->user;
        $username = $user['username'];
        $condition = array(
            'sender' => $sender,
            'receiver' => $username
        );
        $value = array(
            'message_number' => 0
        );
        $result = $this->ChatSession->update($condition, $value);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '操作成功！';
        } else {
            $data['msg'] = '操作失败！';
        }
        echo json_encode($data);
    }
    
    // 获取用户备注
    public function getComment()
    {
        $userId = $_REQUEST['userId'];
        $comment = $this->ChatComment->getComment($userId);
        
        if ($comment) {
            $data['code'] = 1;
            $data['msg'] = '查询成功';
            $data['data'] = $comment;
        } else {
            $data['code'] = 0;
            $data['msg'] = '未查询到结果';
        }
        echo json_encode($data);
    }

//保存增加的备注
    public function addComment()
    {
        $insertData = array();
        if (empty($_REQUEST['commenterId']) && empty($_REQUEST['userId']) && empty($_REQUEST['comment'])) {
            $data['code'] = 0;
            $data['msg'] = '添加失败';
            echo json_encode($data);
            return false;
        }
        $user = $this->session->user;
        ;
        $insertData['commenter_id'] = $user['id'];
        $insertData['user_id'] = $_REQUEST['userId'];
        $insertData['comment'] = $_REQUEST['comment'];
        $insertData['update_time'] = time();
        $result = $this->ChatComment->insert($insertData);
        if ($result) {
            $res = $this->ChatComment->find($insertData);
            $res[0]['update_time'] = date('Y-m-d H:i:s', $res[0]['update_time']);
            $data['data'] = $res[0];
            $data['code'] = 1;
            $data['msg'] = '添加成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '添加失败';
        }
        echo json_encode($data);
    }

//保存编辑的commment
    public function editComment()
    {
        $updateData = array(
           'comment' => $_REQUEST['comment'],
           'update_time' => time(),
           'commenter_id'=>$_SESSION['user']['id']
       );
       $commentId = $_REQUEST['commentId'];
       $result = $this->ChatComment->update(array(
           'id' => $commentId
       ), $updateData);
       if ($result) {
           $updateData['update_time'] = date('Y-m-d H:i:s', $updateData['update_time']);
           $updateData['commenter'] = $_SESSION['user']['username'];
           $data['data'] = $updateData;
           $data['code'] = 1;
           $data['msg'] = '修改成功';
       } else {
           $data['code'] = 0;
           $data['msg'] = '修改失败';
       }
       echo json_encode($data);
    }
    
    // 删除用户备注
    public function deleteComment()
    {
        $commentId = $_REQUEST['commentId'];
        $result = $this->ChatComment->logicDelete($commentId);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '删除成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '删除失败';
        }
        echo json_encode($data);
    }
    
    // 获取用户详情
    public function getCustomerInfo()
    {
        $result = $this->CustomerInfo->getCustomerInfo($_REQUEST['userId']);
        if ($result) {
            $data['data'] = $result;
            $data['code'] = 1;
            $data['msg'] = '查询成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '未查询到结果';
        }
        echo json_encode($data);
    }

    /* 判断用户是否在线 */
    private function isOnline($userid)
    {
        if (empty($this->redis)) {
            $this->load->helper('redis');
            $redis = getRedis('default');
            if (false === $redis) {
                return false;
            }
        }
        
        $connection = $redis->hGet(REDIS_HASH_USER_CONNECTION, $userid);
        if ($connection) {
            return true;
        } else {
            return false;
        }
    }
}
